window.addEventListener('load', () => {
    //获取变量
    const dataMain = document.querySelector('.columns .container')
    const shopList = document.querySelector('.form .wrapper')
    const titItem = document.querySelector('.tit-wrapper')
    const clear = document.querySelector('.cart-out .clear')
    const peiSong = document.querySelector('.peisong .days')
    const jieSuan = document.querySelector('#sendIsCAC')
    const xiaoji = document.querySelector('.totals .price-all')
    const zongjia = document.querySelector('.totals .price-total')
        //判断是否登陆，未登录，跳到登陆页面，登陆继续
    var uid = cookie('uname')
    if (!uid) {
        alert('还没有登陆，非法进入，请登录！！！')
        location.href = './login.html'
    }
    //获取本地存储数据
    var str = localStorage.getItem('data')
        //判断本地存储中有没有数据
    if (!str) {
        var str = `
        <h1>购物车空空如也，快去添加心仪的商品吧！！！</h1>
        <a href='./list.html'>回到首页</a>
        `
        dataMain.innerHTML = str
    }
    //有数据，转成数组，请求数据，将本地存储的id对应的商品列出来
    var arr = JSON.parse(str)
    promiseAjax({
            url: './json/daierData.json',
        }).then(res => {
            var date = []
            for (var i = 0; i < res.length; i++) {
                for (var j = 0; j < arr.length; j++) {
                    if (res[i].pid == arr[j].id) {
                        date.push(res[i])
                    }
                }
            }
            //找到对应商品后，将商品信息渲染到页面
            getInner(date)
        })
        //点击结账按钮事件
    jieSuan.addEventListener('click', () => {
        alert('恭喜您，已付款成功！！！')
    })

    //渲染数据的方法
    function getInner(date) {
        var inner = ''
        var song = ''
        var n = 0
        for (var i = 0; i < date.length; i++) {
            inner += `
            <table class="table">
                <tbody class="tbody">
                         <tr class="info">
                             <td class="col">
                                 <a href="javascript:;" class="computer">
                                     <img src="https:${date[i].psimg}">
                                 </a>
                                 <div class="details">
                                     <strong class="name">
                                         <a href="javascript:;">${date[i].pstitle} ${date[i].cpu} （${date[i].monitor} /${date[i].Memory}）</a>
                                         <div class="sku">
                                             <span>商品编号：</span>${date[i].Eval}
                                         </div>
                                     </strong>
                                     <div class="pro-cart">
                                         <div class="pro-label">
                                             <div>详情</div>
                                         </div>
                                         <div class="pro-con hide">
                                             <ul>
                                                 <li class="cpu">${date[i].cpu}</li>
                                                 <li class="win">${date[i].win}</li>
                                                 <li class="Memory">${date[i].Memory}</li>
                                                 <li class="Gcard">${date[i].Gcard}</li>
                                                 <li class="hardDisk">${date[i].hardDisk}</li>
                                                 <li class="pingfen">${date[i].pingfen}</li>
                                             </ul>
                                         </div>
                                     </div>
                                     <div class="include">包括</div>
                                     <dl class="option">
                                         <dd>
                                             <div class="new">
                                                 <div class="name">惠普有线包鼠套装</div>
                                                 <img src="https://media.hpstore.cn/catalog/product/cache/dc09e1c71e492175f875827bcbf6a37c/4/q/4qm77_-_1_.png">
                                             </div>
                                         </dd>
                                     </dl>
                                     <div class="message">
                                         日常销售价${date[i].yuanjia}，抢购价${date[i].price} </div>
                                     <div class="youhui">
                                         国庆优惠价，限时限量抢购！ </div>
                                     <span class="s-time hide">交货需要2-5个工作日</span>
                                 </div>
                             </td>
                             <td class="col sub">
                                 <div class="amount">
                                     <span class="price-tax">
                                         <div class="sug-price">
                                             <del class="old-p">${date[i].yuanjia}</del>
                                             <span class="sale">节省&nbsp; ${date[i].zhekou}</span>
                                 </div>
                                 <span class="new-p " style="color:red;">&nbsp; ${date[i].price}</span>
                                 </span>
             </div>
             <div class="num-count">
                 <span class="reduce">-</span>
                 <div><input type="text" value="1" class='shopN'></div>
                 <span class="add">+</span>
             </div>
             <div class="del">
                 <a href="javascript:;" class="delete">移除商品</a>
             </div>
             </td>
             </tr>
             </tbody>
             </table>
            `
            song += `
             <dl>
                <dt style="font-weight:600;font-size:18px;">${date[i].pstitle} ${date[i].cpu} （${date[i].monitor} /${date[i].Memory})</dt>
                <dd>
                    <span class="yuan"></span>
                    <span>有货</span>
                    <span style="font-size:14px;">优先选择顺丰发货,预计到货时间1天。如果顺丰不支持配送,将选择EMS发货,预计到货时间1-2天</span>
                </dd>
            </dl>
            `
        }
        var num = `
        <h1 class="page-tit">
                    <span class="base">购物车</span>
                    <p class="tit-items" style="font-size:18px;">${date.length} 物品</p>
                </h1>
        `
            //添加内容
        shopList.innerHTML = inner
        peiSong.innerHTML = song
        titItem.innerHTML = num
            //点击加减按钮，里面的数字发生变化
        getNum()
            //计算总价
        getTotal()
            //删除商品
        delShop()
    }
    //加减数量的方法
    function getNum() {
        //获取变量
        const reduce = document.querySelectorAll('.reduce')
        const add = document.querySelectorAll('.add')
        const shopN = document.querySelectorAll('.shopN')
        for (let i = 0; i < reduce.length; i++) {
            //点击减号时，输入框的值--，最小为1
            reduce[i].addEventListener('click', () => {
                //判断输入框是否为最小，不是可--，是就不变
                if (shopN[i].value == 1) {
                    shopN.value = 1
                } else {
                    shopN[i].value--
                }
                //点击一次调用一次计算总价
                getTotal()
            })
        }
        for (let i = 0; i < add.length; i++) {
            //点击加号，输入框的值++，最大为1000
            add[i].addEventListener('click', () => {
                //判断输入框是否为最大，不是可++，是就不变
                if (+shopN.value >= 1000) {
                    shopN[i].value = 1000
                } else {
                    shopN[i].value++
                }
                //点击一次调用一次计算总价
                getTotal()
            })
        }
        for (let i = 0; i < shopN.length; i++) {
            //可输入数字，失去焦点时，值最小1，最大1000
            shopN[i].addEventListener('blur', function() {
                if ((+this.value) >= 1000) {
                    this.value = 1000
                }
                if ((+this.value) <= 1) {
                    this.value = 1
                }
                getTotal()
            })
        }
    }
    //计算总价的方法
    function getTotal() {
        //获取总的数量和价格
        const shopN = document.querySelectorAll('.shopN')
        const price = document.querySelectorAll('.new-p')
            //计算总价
        var sum = 0
            //正则
        var reg = /\d+[\.]\d+/
        for (var i = 0; i < shopN.length; i++) {
            var p = reg.exec(price[i].innerText)
            sum += (+shopN[i].value) * (+p[0])
        }
        sum = toDecimal2(sum)
        sum = '￥' + sum
            //把sum渲染到小计和总价中
        xiaoji.innerText = zongjia.innerText = sum
    }
    //移除商品的方法
    function delShop() {
        const del = document.querySelectorAll('.del .delete')
        for (let i = 0; i < del.length; i++) {
            del[i].onclick = function() {
                // var str = localStorage.getItem('data')
                // var arr = JSON.parse(str)
                if (confirm('您确定要删除这件商品嘛？')) {
                    this.parentElement.parentElement.parentElement.remove()
                    getTotal()
                        // console.log(JSON.parse(localStorage.data)[i].id);
                        // localStorage.removeItem(JSON.parse(localStorage.data)[i].id)
                    alert('删除成功！')
                }
            }
        }
    }
    delCart()
        //清除购物车的方法
    function delCart() {
        clear.addEventListener('click', () => {
            //先确是否真的要清空购物车
            if (confirm('清空购物车就什么都没有了哦，您确定要这么做吗？')) {
                localStorage.clear()
                alert('清空成功！')
            }
        })
    }
    //2.强制保留2位小数，如：2，会在2后面补上00.即2.00
    function toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s;
    }
})